package com.xianbeiying.app.ckgl.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.xianbeiying.app.ckgl.MyApplication;
import com.xianbeiying.app.ckgl.R;
import com.xianbeiying.app.ckgl.adapter.CpChoiceContentdapter;
import com.xianbeiying.app.ckgl.adapter.CpContentdapter;
import com.xianbeiying.app.ckgl.adapter.CpTypeadapter;
import com.xianbeiying.app.ckgl.adapter.GridSelectImageAdapter;
import com.xianbeiying.app.ckgl.bean.CreatCropTypeBean;
import com.xianbeiying.app.ckgl.bean.CreateCropBean;
import com.xianbeiying.app.ckgl.bean.CropsBean;
import com.xianbeiying.app.ckgl.http.HttpCallBackUtil;
import com.xianbeiying.app.ckgl.model.GetModel;
import com.xianbeiying.app.ckgl.model.SetModel;
import com.xianbeiying.app.ckgl.photo.activity.PhotoPagerActivity;
import com.xianbeiying.app.ckgl.photo.activity.PhotoPickerActivity;
import com.xianbeiying.app.ckgl.photo.util.PhotoPickerIntent;
import com.xianbeiying.app.ckgl.util.BitmapAndStringUtils;
import com.xianbeiying.app.ckgl.util.LogUtils;
import com.xianbeiying.app.ckgl.util.StringUtil;
import com.xianbeiying.app.ckgl.util.ToastUtil;
import com.xianbeiying.app.ckgl.widght.MyGridView;
import com.xianbeiying.app.ckgl.widght.popwindow.CenterPopWindow;

import java.util.ArrayList;
import java.util.List;

/**
 * 选择农作物
 */
public class ChoicePlantActivity extends BaseActivity implements View.OnClickListener, HttpCallBackUtil {
    private ImageView iv_title_left;
    private TextView tv_title;
    private ListView rv_plant_type;
    private GridView rv_plant_content;
    private CpChoiceContentdapter cpChoicecontentadapter;
    private CpContentdapter cpContentadapter;
    private CpTypeadapter cpTypeadapter;
    private LinearLayout ly_cp_button;
    private RecyclerView recyclerView;
//  private String[] typeStr = {"叶根类", "根茎类", "茄果类", "白菜类", "豆类", "薯芋类", "花菜类", "食用菌", "瓜类", "其他类"};
//  private String[] sp = {"白菜", "青菜", "芹菜", "韭菜"};
    private Button btn_cp;
    private CenterPopWindow centerPopWindow,plantTypePopWindow;
    private MyGridView ivplant_list;
    private GridSelectImageAdapter gridSelectImageAdapter;
    private static final int ADD_CHOOSE = 0;
    private static final int MODIFY_CHOOSE = 1;
    private static final int MAX_PIC_NUM = 1;
    private ArrayList<String> imgPaths = new ArrayList<>();
    private boolean isMulti;
    private GetModel getModel;
    private SetModel setModel;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        isPermisson=true;
        setContentView(R.layout.activity_choice_plant);
        initView();
    }

    private int fristSelectId = 0;
    private int selectId=0;
    private Intent intent;

    private void initView() {
        intent = new Intent();
        getModel = new GetModel(this);
        getModel.addResponseListener(this);
        setModel=new SetModel(this);
        setModel.addResponseListener(this);
        iv_title_left = (ImageView) findViewById(R.id.iv_title_left);
        tv_title = (TextView) findViewById(R.id.tv_title);
        ly_cp_button = (LinearLayout) findViewById(R.id.ly_cp_button);
        btn_cp = (Button) findViewById(R.id.btn_cp);
        tv_title.setText("选择农作物");
        iv_title_left.setOnClickListener(this);
        rv_plant_type = (ListView) findViewById(R.id.rv_plant_type);
        rv_plant_content = (GridView) findViewById(R.id.rv_plant_content);
        recyclerView = (RecyclerView) findViewById(R.id.rv_choice_content);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        // 设置布局管理器
        recyclerView.setLayoutManager(layoutManager);
        //去掉RecyclerView滑到边界产生的蓝色阴影
        recyclerView.setOverScrollMode(View.OVER_SCROLL_NEVER);
        initData();
    }

    private void initData() {
        if(MyApplication.cropsBean!=null){
            cropsBean=MyApplication.cropsBean;
            setAdapter();
        }else{
            getModel.GETALLCrops("GET_CROPS", true);
        }
        initEvent();
    }

    private ArrayList<String> choiceList = new ArrayList<>();
    private ArrayList<String> choiceId=new ArrayList<>();
    private ArrayList<String> cropId=new ArrayList<>();
    private void initEvent() {
        btn_cp.setOnClickListener(this);
        //右边内容
        rv_plant_content.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (cpContentadapter.getArrayListBoolean().get(position)){
                    cpContentadapter.getArrayListBoolean().set(position, false);
                }else{
                    cpContentadapter.getArrayListBoolean().set(position, true);
                }
                cpContentadapter.notifyDataSetChanged();
                int size = cropsBean.getV().getALLCROPS().get(fristSelectId).getCrops().size();
                choiceList.clear();
                choiceId.clear();
                cropId.clear();
                for (int i = 0; i < size; i++){
                    if (cpContentadapter.getArrayListBoolean().get(i)) {
                        choiceList.add(cropsBean.getV().getALLCROPS().get(fristSelectId).getCrops().get(i).getCropName());
                        choiceId.add(cropsBean.getV().getALLCROPS().get(fristSelectId).getCrops().get(i).getCropId()+"");
                        cropId.add(cropsBean.getV().getALLCROPS().get(fristSelectId).getCrops().get(i).getCropType()+"");
//                        LogUtils.e("----", sp[i]);
                    }
                }
                if (choiceList.size() != 0){
                    ly_cp_button.setVisibility(View.VISIBLE);
                    cpChoicecontentadapter = new CpChoiceContentdapter(ChoicePlantActivity.this);
                    cpChoicecontentadapter.setArrayList(choiceList);
                    recyclerView.setAdapter(cpChoicecontentadapter);
                } else {
                    ly_cp_button.setVisibility(View.GONE);
                }
                selectId=position;
            }
        });
    }
   private EditText et_plant_type_name;
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                //分类
                case R.id.tv_cp_type:
                    fristSelectId = msg.arg1;
                    int size = cpTypeadapter.getArrayListBoolean().size();
                    for (int i = 0; i < size; i++) {
                        if(i == msg.arg1){
                            cpTypeadapter.getArrayListBoolean().set(i, true);
                        }else{
                            cpTypeadapter.getArrayListBoolean().set(i, false);
                        }
                    }
                    cpTypeadapter.notifyDataSetChanged();
                    cpContentadapter = new CpContentdapter(ChoicePlantActivity.this, cropsBean.getV().getALLCROPS().get(msg.arg1).getCrops(), "种植");
                    cpContentadapter.setArrayListBoolean(StringUtil.getList(cropsBean.getV().getALLCROPS().get(msg.arg1).getCrops().size()));
                    rv_plant_content.setAdapter(cpContentadapter);
                    cpContentadapter.setHandler(handler);
                    break;
                //添加作物类型
                case R.id.tv_cp_add:
                    plantTypePopWindow=new CenterPopWindow(ChoicePlantActivity.this, R.layout.pop_window_plant_type);
                    et_plant_type_name=plantTypePopWindow.getView(R.id.et_plant_type_name);
                    plantTypePopWindow.setTextOnClickListener(R.id.plant_type_done,ChoicePlantActivity.this);
                    plantTypePopWindow.setTextOnClickListener(R.id.ly_type_plant,ChoicePlantActivity.this);
                    break;
                //添加作物
                case R.id.iv_cp_add:
                    centerPopWindow = new CenterPopWindow(ChoicePlantActivity.this, R.layout.pop_window_plant);
                    centerPopWindow.setTextOnClickListener(R.id.done, ChoicePlantActivity.this);
                    centerPopWindow.setTextOnClickListener(R.id.ly_pop_plant, ChoicePlantActivity.this);
                    ivplant_list = centerPopWindow.getView(R.id.ivplant_list);
                    et_plant_name=centerPopWindow.getView(R.id.et_plant_name);
                    gridSelectImageAdapter = new GridSelectImageAdapter(ChoicePlantActivity.this, imgPaths, MAX_PIC_NUM);
                    //加载数据
                    ivplant_list.setAdapter(gridSelectImageAdapter);
                    ivplant_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            if (position < imgPaths.size()) {
                                Intent intent = new Intent(ChoicePlantActivity.this, PhotoPagerActivity.class);
                                intent.putExtra(PhotoPagerActivity.EXTRA_CURRENT_ITEM, position);
                                intent.putExtra(PhotoPagerActivity.EXTRA_PHOTOS, imgPaths);
                                startActivityForResult(intent, MODIFY_CHOOSE);
                            } else {
                                //Add Photo
                                PhotoPickerIntent intent = new PhotoPickerIntent(ChoicePlantActivity.this);
                                intent.setPhotoCount(MAX_PIC_NUM - imgPaths.size());
                                intent.setMultiChoose(isMulti);
                                startActivityForResult(intent, ADD_CHOOSE);
                            }
                        }
                    });
                    break;
            }
        }
    };

    private EditText et_plant_name;
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_title_left:
                finish();
                break;
            //确定
            case R.id.btn_cp:
                if (choiceList.size() != 0) {
                    String zw = StringUtil.getAddres(choiceList);
                    intent.setClass(ChoicePlantActivity.this, PlantCropActivity.class);
                    intent.putExtra("zw", zw);
                    intent.putStringArrayListExtra("zwlist",choiceList);
                    intent.putStringArrayListExtra("choiceId",choiceId);
                    intent.putStringArrayListExtra("cropTypeId",cropId);
                    intent.putExtra("zwId",cropsBean.getV().getALLCROPS().get(fristSelectId).getCrops().get(selectId).getCropId());
                    setResult(20, intent);
                    finish();
                }
                break;
            //添加作物类型
            case R.id.plant_type_done:
                String plantType=et_plant_type_name.getText().toString().trim();
                if(plantType.isEmpty()){
                    ToastUtil.showInfo(ChoicePlantActivity.this,"请输入作物类型");
                    return;
                }
                setModel.CREATE_CROP_TYPE("CREATE_CROP_TYPE",plantType,true);
                plantTypePopWindow.dismiss();
                break;
            case R.id.ly_type_plant:
                plantTypePopWindow.dismiss();
                break;
            //关闭
            case R.id.ly_pop_plant:
                centerPopWindow.dismiss();
                break;
            //添加其他作物
            case R.id.done:
                String plantName=et_plant_name.getText().toString().trim();
                if(plantName.isEmpty()){
                    ToastUtil.showInfo(ChoicePlantActivity.this,"请输入作物名称");
                    return;
                }
                if(imgPaths.size()==0){
                    ToastUtil.showInfo(ChoicePlantActivity.this,"请添加图片");
                    return;
                }
                Bitmap bitmap = StringUtil.getLoacalBitmap(imgPaths.get(0));
                String url=null;
                if(imgPaths.get(0).contains(".png")){
                    url="png;"+ BitmapAndStringUtils.convertIconToString(bitmap);
                }
                if(imgPaths.get(0).contains(".jpg")){
                    url="jpg;"+BitmapAndStringUtils.convertIconToString(bitmap);
                }
                LogUtils.e("000",imgPaths.get(0)+"-----");
                LogUtils.e("0000",url);
                setModel.CREATE_CROP("CREATE_CROP",cropsBean.getV().getALLCROPS().get(fristSelectId).getCropType(),plantName,url,true);
                centerPopWindow.dismiss();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        List<String> photos = null;
        if (resultCode == RESULT_OK && requestCode == MODIFY_CHOOSE) {
            if(data != null){
                photos = data.getStringArrayListExtra(PhotoPickerActivity.KEY_SELECTED_PHOTOS);
            }
            imgPaths.clear();
            if (photos != null) {
                imgPaths.addAll(photos);
            }
            gridSelectImageAdapter.notifyDataSetChanged();
        } else if (resultCode == RESULT_OK && requestCode == ADD_CHOOSE) {
            if (data != null) {
                photos = data.getStringArrayListExtra(PhotoPickerActivity.KEY_SELECTED_PHOTOS);
            }
            if (photos != null) {
                imgPaths.addAll(photos);
            }
            gridSelectImageAdapter.notifyDataSetChanged();
        }
    }

    private CropsBean cropsBean;
    private CreatCropTypeBean creatCropTypeBean;
    private CreateCropBean createCropBean;
    @Override
    public void onCallBackData(String url, Object content){
        if (url.equals("农作物")){
            if (content != null){
                cropsBean = JSON.parseObject(new String((byte[]) content), CropsBean.class);
                MyApplication.cropsBean = cropsBean;
                setAdapter();
            }
        }

        if (url.equals("创建作物")){
            if (content != null){
                createCropBean = JSON.parseObject(new String((byte[]) content), CreateCropBean.class);
                if(createCropBean.isR()){
                    ToastUtil.showInfo(ChoicePlantActivity.this,"添加成功");
                    getModel.GETALLCrops("GET_CROPS", false);
                }else{
                    ToastUtil.showInfo(ChoicePlantActivity.this,createCropBean.getERR_MSG());
                }
            }
        }

        if (url.equals("创建作物类型")){
            if (content != null){
                creatCropTypeBean = JSON.parseObject(new String((byte[]) content), CreatCropTypeBean.class);
                if(creatCropTypeBean.isR()){
                    ToastUtil.showInfo(ChoicePlantActivity.this,"添加成功");
                    getModel.GETALLCrops("GET_CROPS", false);
                }else{
                    ToastUtil.showInfo(ChoicePlantActivity.this,creatCropTypeBean.getERR_MSG());
                }
            }
        }
    }
    private void setAdapter() {
        cpChoicecontentadapter = new CpChoiceContentdapter(this);
        cpContentadapter = new CpContentdapter(this, cropsBean.getV().getALLCROPS().get(fristSelectId).getCrops(),"种植");
        cpContentadapter.setArrayListBoolean(StringUtil.getList(cropsBean.getV().getALLCROPS().get(fristSelectId).getCrops().size()));
        cpTypeadapter = new CpTypeadapter(this, cropsBean,"种植");
        cpTypeadapter.setArrayListBoolean(StringUtil.getCropArryList(cropsBean,fristSelectId));
        rv_plant_type.setAdapter(cpTypeadapter);
        rv_plant_content.setAdapter(cpContentadapter);
        cpTypeadapter.setHandler(handler);
        cpContentadapter.setHandler(handler);
    }
}
